package com.cxf.service.impl;

import com.cxf.dao.OrderDao;
import com.cxf.dao.ProductDao;
import com.cxf.dao.UserDao;
import com.cxf.pojo.Order;
import com.cxf.pojo.Product;
import com.cxf.pojo.User;
import com.cxf.service.OrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("orderServiceImpl")
public class OrderServiceImpl implements OrderService {

	@Resource(name="orderDaoImpl")
	private OrderDao orderDao = null;
	@Resource(name = "productDaoImpl")
	private ProductDao productDao;
    @Resource(name = "userDaoImpl")
    private UserDao userDao;

	@Override
	public int insertOrder(Order order) {
		return orderDao.insertOrder(order);
	}

	public OrderDao getOrderDao() {
		return orderDao;
	}

	@Override
	public List<Order> getOrderByUserName(String userName) {
		return orderDao.getOrderByUserName(userName);
	}

    @Override
    public Order getOrderById(Integer id) {
        return orderDao.getOrderById(id);
    }

    /**
     * 取消订单
     * @param orderId
     */
    @Override
    public void cancelOrder(Integer orderId) {
        //获取订单
        Order order = orderDao.getOrderById(orderId);
        //返还库存
        Integer productId = order.getProduct().getId();
        Product product = productDao.getProductById(productId);
        product.setStock(product.getStock() + order.getAmount());
        productDao.updateProduct(product);
        //返还金额
        Integer userId = order.getUserId();
        User user = userDao.getUserById(userId);
        user.setBalance(user.getBalance() + order.getSumPrice());
        userDao.updateUser(user);
        //修改订单状态
        order.setStatus(0);
        orderDao.updateOrder(order);
    }

    public void setOrderDao(OrderDao orderDao) {
		this.orderDao = orderDao;
	}

}
